import os
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
input ="Z:\\贤儿Sherry"
output = "E:\\datasets\\val\\"
num=1
def c2bw(outputfile,inputfile):
    try:
        img = Image.open(inputfile)
    except BaseException:
        print(inputfile + "  error")
        # os.remove(inputfile)
        return
    w = img.size[0]
    h = img.size[1]
    #切割成正方形
    if h > w:
        offset = int(h - w) / 2
        outcolor = img.crop((0,offset,w,offset+w))
    else:
        offset = int(w - h) / 2
        outcolor = img.crop((offset,0,offset+h,h))
    # 图片缩小
    outcolor = outcolor.resize((128, 128), Image.ANTIALIAS).convert('RGB')

    outcolor.save(outputfile, 'JPEG')
    # 图片黑白
    # outbw = outcolor.convert('L')
    # outbw.save(outputbw + inputfile, 'JPEG')
def is_img(ext):
    ext = os.path.splitext(ext)[1]
    ext =ext.lower()
    if ext == '.jpg':
        return True
    elif ext == '.png':
        return True
    elif ext == '.jpeg':
        return True
    elif ext == '.bmp':
        return True
    else:
        return False

def all_path(dirname):

    result = []#所有的文件
    for maindir, subdir, file_name_list in os.walk(dirname):

        # print("1:",maindir) #当前主目录
        # print("2:",subdir) #当前主目录下的所有目录
        # print("3:",file_name_list)  #当前主目录下的所有文件
        for filename in file_name_list:
            if is_img(filename):#是图片
                apath = os.path.join(maindir, filename)#合并成一个完整路径
                result.append(apath)
    return result

input_images = all_path(input)
print(len(input_images))



for input_image in input_images:
    filename = str(num).zfill(9) + ".jpg"
    print(input_image+"  to  "+filename)
    if not os.path.exists(output + filename):
        c2bw(output + filename,input_image)
    num+=1